#!/usr/bin/python

import gdb;

def tfind_entry(num):
	if num < 0:
		tid = gdb.execute("tfind", False, True);
	else:
		tid = gdb.execute("tfind "+str(num), False, True);
	if tid.find(", tracepoint ") < 0:
		return -1;
	tid = tid[tid.find(", tracepoint ") + len(", tracepoint "):];
	return int(tid);

gdb.execute("set pagination off", True, True);

#Set to the begin
gdb.execute("tfind -1", False, True);

f = {};
cc = {};
cr = {};
pe00 = {};
pe01 = {};
pe02 = {};
pe03 = {};
pe04 = {};
pe05 = {};
pe06 = {};
count = {};

cpu_number = gdb.parse_and_eval("$cpu_number");
cpu_number = int(cpu_number);
for i in range(0, cpu_number):
	f[i] = file("f"+str(i)+".csv", 'w');
	cc[i] = 0;
	cr[i] = 0;
	pe00[i] = 0;
	pe01[i] = 0;
	pe02[i] = 0;
	pe03[i] = 0;
	pe04[i] = 0;
	pe05[i] = 0;
	pe06[i] = 0;
	count[i] = 0;


while 1:
	try:
		tid = tfind_entry(-1);
		if tid < 0:
			break;

		cpu_id = gdb.parse_and_eval("$cpu_id");
		cpu_id = int(cpu_id);
		if cpu_id >= cpu_number:
			raise gdb.error ("CPU id is too big.");
		tmp = gdb.parse_and_eval("$pc_cc_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		cc[cpu_id] += tmp;
		tmp = gdb.parse_and_eval("$pc_cr_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		cr[cpu_id] += tmp;
		tmp = gdb.parse_and_eval("$pc_pe_val_00_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		pe00[cpu_id] += tmp;
		tmp = gdb.parse_and_eval("$pc_pe_val_01_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		pe01[cpu_id] += tmp;
		tmp = gdb.parse_and_eval("$pc_pe_val_02_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		pe02[cpu_id] += tmp;
		tmp = gdb.parse_and_eval("$pc_pe_val_03_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		pe03[cpu_id] += tmp;
		tmp = gdb.parse_and_eval("$pc_pe_val_04_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		pe04[cpu_id] += tmp;
		tmp = gdb.parse_and_eval("$pc_pe_val_05_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		pe05[cpu_id] += tmp;
		tmp = gdb.parse_and_eval("$pc_pe_val_06_"+str(cpu_id));
		f[cpu_id].write(str(tmp)+",");
		pe06[cpu_id] += tmp;
		f[cpu_id].write("\n");
		count[cpu_id]+=1;
	except gdb.error, x:
		print("Drop one entry because", x);
		break;
	except gdb.MemoryError, x:
		print("Drop one entry because", x); 
		break;

for i in range(0, cpu_number):
	f[i].write("\n");
	f[i].write(str(cc[i]/count[i])+",");
	f[i].write(str(cr[i]/count[i])+",");
	f[i].write(str(pe00[i]/count[i])+",");
	f[i].write(str(pe01[i]/count[i])+",");
	f[i].write(str(pe02[i]/count[i])+",");
	f[i].write(str(pe03[i]/count[i])+",");
	f[i].write(str(pe04[i]/count[i])+",");
	f[i].write(str(pe05[i]/count[i])+",");
	f[i].write(str(pe06[i]/count[i])+",");
	f[i].write("\n");
	f[i].write(str(count[i])+"\n");
	f[i].close()
